<?php

/**
 * ExtYiiModelReaderBase class file
 *
 * @author TrueSoftware B.V. (The Netherlands)
 * @link http://www.ext4yii.com
 * @copyright Copyright 2007-2010 TrueSoftwareB.V. all rights reserved.
 * @license http://www.ext4yii.com/license/
 *          EVALUATION VERSION - NOT FOR COMMERCIAL USE OR DISTRIBUTION.
 * @version 0.7.2
 */
class ExtYiiModelReaderBase extends ExtJsonReader
{

    public function parseNode(ExtHTMLParserNode $node, ExtASTWalker $astwalker)
    {
        parent::parseNode($node, $astwalker);
        $this->parseModel($astwalker);
    }

    private function parseModel($astwalker)
    {
        $obj = null;
        $fields = array();
        $model = $this->getModel();
        $class = new ReflectionClass($model);
        $bases = (array) $class->getParentClass();
        $delegatefn = $this->getColumnDelegate();
        $hasdelegate = method_exists($this->getController(), $delegatefn);
        $controller = $this->getController();

        if (array_search('CActiveRecord', $bases))
        {
            // invoking mymodel::model()
            $obj = call_user_func(array($model, 'model'));
            foreach ($obj->metaData->columns as $column)
            {
                $field = new ExtReaderField();
                $field->setController($this->getController());
                $field->setAstWalker($astwalker);
                $field->setName($column->name);
                if($hasdelegate)
                {
                    call_user_func_array(array($controller,$delegatefn), array($field,$column));
                }
                $fields[] = $field->renderConfig(false);
            }
        }
        else if (array_search('CFormModel', $bases))
        {
            $obj = new $model();
            foreach ($obj->attributeNames() as $column)
            {
                $field = new ExtReaderField();
                $field->setName($column);
                $field->setController($this->getController());
                $field->setAstWalker($astwalker);
                $fields[] = $field->renderConfig(false);
            }
        }
        else
        {
            throw new Exception(
                    Ext4Yii::t('ext4yii',
                            'The provided model "{model} is neither an CActiveRecord nor CFormModel!"',
                            array('{mode}' => $this->getModel()
                    )));
        }

        if (count($fields) != 0)
            $this->setArrayConfig('fields', $fields);
    }

    public function renderConfig($asobject=true)
    {
        $this->deleteConfig('model');
        return parent::renderConfig($asobject);
    }
}

?>
